<!DOCTYPE html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1.0, maximum-scale=1.0" />
	<style type="text/css">
		body {
			background: #00CCCC;
		}
		.welcome {
			position: absolute;
			top: 0;
			left: 0;
			width: 320px;
			height: 460px;
			z-index: 8;
		}
	</style>
	<title>单canvas实现刮刮卡</title>
</head>

<body>
	<canvas class="welcome"></canvas>
</body>

<script type="text/javascript">
	(function(bodyStyle) {

		bodyStyle.mozUserSelect = 'none';
		bodyStyle.webkitUserSelect = 'none';

		var canvas = document.querySelector('canvas');
		var canvasStyle = canvas.style;
		canvasStyle.backgroundColor = 'transparent';

		var img = new Image();
		img.src = 'images/welcome.jpg';

		img.addEventListener('load', function(e) {

			var w = 320, h = 460;
			var mousedown = false;

			canvas.width = w;
			canvas.height = h;

			var ctx = canvas.getContext('2d');
			ctx.fillStyle = 'transparent';

			ctx.fillStyle = 'gray';
			ctx.fillRect(0, 0, w, h);
			ctx.drawImage(img, 0, 0, w, h);

			// 在已有内容和新图形不重叠的地方，已有内容保留，所有其他内容成为透明。
			ctx.globalCompositeOperation = 'destination-out';

			function eventDown(e) {
				e.preventDefault();
				mousedown = true;
			}

			function eventMove(e) {
				e.preventDefault();
				if (mousedown) {
					if (e.changedTouches) {
						// 取得涉及当前事件中众多手指中的最后一个。
						e = e.changedTouches[e.changedTouches.length - 1];
					}
					var x = (e.clientX + document.body.scrollLeft || e.pageX) - canvas.offsetLeft || 0, y = (e.clientY + document.body.scrollTop || e.pageY) - canvas.offsetTop || 0;
					with (ctx) {
						beginPath();
						arc(x, y, 25, 0, Math.PI * 2);
						fill();
					}
				}
			}

			function eventUp(e) {
				e.preventDefault();
				mousedown = false;
				var data = ctx.getImageData(0, 10, w, h).data;
				for (var i = 0, j = 0; i < data.length; i += 4) {
					if (data[i] && data[i + 1] && data[i + 2] && data[i + 3]) {
						j++;
					}
				}
				if (j <= w * h * 0.6) {
					ctx.clearRect(0, 0, w, h);
				}
			}


			canvas.addEventListener('touchstart', eventDown);
			canvas.addEventListener('touchend', eventUp);
			canvas.addEventListener('touchmove', eventMove);
			canvas.addEventListener('mousedown', eventDown);
			canvas.addEventListener('mouseup', eventUp);
			canvas.addEventListener('mousemove', eventMove);
		});

	})(document.body.style);

</script>

</html>
